package cn.xd.learn.itstack.dbatis.spring;

import cn.xd.learn.itstack.dbatis.config.SqlSessionFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.FactoryBean;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

/**
 * @Classname MapperFactoryBean
 * @Description TODO
 * @Date 2022/4/26 下午2:58
 * @Created by lvxiaodong
 */
@Slf4j
public class MapperFactoryBean<T> implements FactoryBean<T> {


    private Class<T> mapperInterface;
    private SqlSessionFactory sqlSessionFactory;

    public MapperFactoryBean(Class<T> mapperInterface, SqlSessionFactory sqlSessionFactory) {
        this.mapperInterface = mapperInterface;
        this.sqlSessionFactory = sqlSessionFactory;
    }


    @Override
    public T getObject() throws Exception {
        //代理方法
        InvocationHandler handler = (proxy, method, args) ->{
            log.info("你被代理了，执行SQL操作");
            try {
                return sqlSessionFactory.openSession().selectOne(mapperInterface.getName()+"."+method.getName(),args[0]);
            }catch (Exception e){
                log.error("执行失败 e" ,e);
            }
            return method.getReturnType().newInstance();
        };
        //代理类
        return (T)Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),new Class[]{mapperInterface},handler);
    }

    @Override
    public Class<?> getObjectType() {
        return mapperInterface;
    }
}
